﻿
CREATE PROCEDURE Sec__CreateSecurityTrigger
	@Table sysname,@TriggerType sysname,@PostFix varchar(1024) = ''
AS

DECLARE @TrName sysname,
				@Index varchar(128),@IndexName varchar(128),
				@Index1 varchar(128),@IndexName1 varchar(128)

SET @TrName = 'trsec_'+@Table+'_'+@TriggerType

if exists (select * from dbo.sysobjects where id = object_id(@TrName) and OBJECTPROPERTY(id, N'IsTrigger') = 1)
EXEC ('drop trigger '+@TrName)

SET @Index = 'SET @Index='''''
EXEC sec__GetColumnInPrimaryKey @Table,2,@Key = @IndexName OUTPUT

IF NOT @IndexName IS NULL BEGIN
	SET @Index = 'SELECT @Index=['+@IndexName+'] FROM inserted'
	SET @IndexName = ','''+@IndexName+''''
END
ELSE
	SET @IndexName = ''

SET @Index1 = 'SET @Index1='''''
EXEC sec__GetColumnInPrimaryKey @Table,3,@Key = @IndexName1 OUTPUT

IF NOT @IndexName1 IS NULL BEGIN
	SET @Index1 = 'SELECT @Index1=['+@IndexName1+'] FROM inserted'
	SET @IndexName1 = ','''+@IndexName1+''''
END
ELSE
	SET @IndexName1 = ''

EXEC ('
CREATE TRIGGER '+@TrName+'
ON dbo.'+@Table+'
FOR '+@TriggerType+'
AS

SET NOCOUNT ON

IF (SELECT COUNT(*) FROM inserted) = 0 RETURN
IF TRIGGER_NESTLEVEL() > 1 RETURN

DECLARE @ApplID int,@Index varchar(50),@Index1 varchar(50)
SELECT @ApplID=ApplicantID FROM inserted
'+@Index+'
'+@Index1+'
'+@PostFix+'
EXEC @ApplID = sec__CheckAccessToApplicant @ApplID,'''+@Table+'''

IF @ApplID > 0 
	EXEC sh_ArchiveRow @ApplID,'''+@Table+''',@Index'+@IndexName+',@Index1'+@IndexName1+'
'
)

EXEC sh_Archive_MakeView @Table

EXEC sp_settriggerorder @TrName, 'first', @TriggerType


